package com.lg.baselibrary.activity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.lg.baselibrary.R;
import com.lg.baselibrary.listener.OnTabItemSelectListener;
import com.lg.baselibrary.widget.BottomTabView;

/**
 * Created by ligang on 2017/5/29.
 * description：
 */

public abstract class BaseBottomFrameLayoutTabActivity extends BaseBottomTabActivity implements OnTabItemSelectListener {
    protected BottomTabView bottomTabView;
    protected FragmentManager fragmentManager;
    @Override
    protected int provideContentViewLayout() {
        return R.layout.activity_base_bottom_tab;
    }

    @Override
    protected void initView() {
        super.initView();
        bottomTabView = findView(R.id.bottomTabView);
        if (getCenterView() == null){
            bottomTabView.setTabItemViews(getTabViews());
        }else {
            bottomTabView.setTabItemViews(getTabViews(), getCenterView());
        }
        fragmentManager = getSupportFragmentManager();
        bottomTabView.setOnTabItemSelectListener(this);
        onTabItemSelect(0);
    }
    private int lastTabIndex = -1;
    @Override
    public void onTabItemSelect(int position) {
        Fragment fragment = fragmentManager.findFragmentByTag(fragments.get(position).getClass().getName());
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if(fragment == null){
            fragment = fragments.get(position);
            transaction.add(R.id.fragmentContainer,fragment,fragment.getClass().getName());
        }else{
            transaction.show(fragment);
        }
        if(lastTabIndex != -1){
            transaction.hide(fragments.get(lastTabIndex));
        }
        transaction.commit();
        lastTabIndex = position;
    }

    /**
     * 是否拦截切换Tab操作
     * 适用场景：有的tab需要登录之后才能切换
     * 子类若要实现该功能，需重写该方法
     * @return true代表拦截切换tab操作
     */
    public boolean onInterceptTabItemSelect(int position){
        return false;
    }
}
